package com.shuosen.gmall.user.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.shuosen.gmall.bean.UserAddress;
import com.shuosen.gmall.bean.UserInfo;
import com.shuosen.gmall.config.RedisUtil;
import com.shuosen.gmall.service.Userservice;
import com.shuosen.gmall.user.mapper.UserAddressMapper;
import com.shuosen.gmall.user.mapper.UserInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.handler.UserRoleAuthorizationInterceptor;
import redis.clients.jedis.Jedis;

import java.util.List;

@Service
public class UserInfoServiceImpl implements Userservice {

    public String userKey_prefix="user:";
    public String userinfoKey_suffix=":info";
    public int userKey_timeOut=60*60*24;


    @Autowired
    private UserInfoMapper userInfoMapper ;

    @Autowired
    private UserAddressMapper userAddressMapper ;

    @Autowired
    private RedisUtil redisUtil   ;



    @Override
    public List<UserInfo> findAll() {

        return  userInfoMapper.selectAll();
    }

    @Override
    public List<UserAddress> findAdressByUserId(String userId) {
        System.out.println("生产者-----------------------");
        UserAddress address = new UserAddress() ;
        address.setUserId(userId);
        return userAddressMapper.select(address);
    }

    @Override
    public UserInfo login(UserInfo userInfo) {
        //需要对密码进行加密
        String password  = userInfo.getPasswd() ;
        //对称加密 和非对称加密
        String newPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        System.out.println("newPassword："+newPassword);
        userInfo.setPasswd(newPassword);
        //用户名密码
        UserInfo info = userInfoMapper.selectOne(userInfo);

        //将用户信息放入缓存当中
        if(info!=null){

            Jedis jedis = redisUtil.getJedis();
            //定义key sku:skuId:skuInfo
            String  userKey = userKey_prefix + info.getId()+userinfoKey_suffix;
            //保存数据 设置过期时间
            jedis.setex(userKey,userKey_timeOut, JSON.toJSONString(info));
            jedis.close();
            return info  ;
        }

        return null;
    }

    @Override
    public UserInfo verfiy(String userId) {
        //如何验证已经登陆
        //获取jedis对象
        Jedis jedis = redisUtil.getJedis();
        //获取数据必须得到key
        String userKey  =  userKey_prefix + userId+userinfoKey_suffix;
        String userJson = jedis.get(userKey);
        if(StringUtils.isNotEmpty(userJson)){
            //需要将userJson转换为字符串
            UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);
            if(userInfo!=null){
                //可以演唱一下用户过期时间
                jedis.expire(userKey,userKey_timeOut);
                jedis.close();
                return  userInfo;
            }
        }
       jedis.close();;
        return null;
    }
}
